/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.convert.vienna.util;

import at.schauer.gregor.vienna.context.ViennaContext;
import at.schauer.gregor.vienna.context.ViennaContextAware;
import at.schauer.gregor.vienna.convert.provider.ConverterProvider;
import at.schauer.gregor.vienna.convert.vienna.SimpleConverter;
import at.schauer.gregor.vienna.convert.vienna.base.SeparatorConverter;

import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

/**
 * @author Gregor Schauer
 */
public class CalendarConverter implements SeparatorConverter<Calendar>, ViennaContextAware {
	protected SimpleConverter<TimeZone> timeZoneConverter;

	@Override
	public Calendar sourceToTarget(String source, Class<? extends Calendar> targetClass) {
		String zoneStr = source.substring(0, source.indexOf(getSeparator()));
		String timeStr = source.substring(zoneStr.length() + 1);
		TimeZone zone = timeZoneConverter.sourceToTarget(zoneStr, TimeZone.class);
		Calendar calendar = Calendar.getInstance(zone, Locale.getDefault());
		calendar.setTimeInMillis(Long.parseLong(timeStr));
		return calendar;
	}

	@Override
	public String targetToSource(Calendar target) {
		return timeZoneConverter.targetToSource(target.getTimeZone()) + getSeparator() + target.getTimeInMillis();
	}

	@Override
	public String getSeparator() {
		return ":";
	}

	@Override
	@SuppressWarnings("unchecked")
	public void setViennaContext(ViennaContext viennaContext) {
		ConverterProvider<SimpleConverter> converterProvider = viennaContext.getConverterProvider(SimpleConverter.class);
		timeZoneConverter = converterProvider.getConverter(TimeZone.class, String.class);
	}

	public void setTimeZoneConverter(SimpleConverter<TimeZone> timeZoneConverter) {
		this.timeZoneConverter = timeZoneConverter;
	}
}
